#include <QDBusArgument>
#include <QByteArray>
#include <QImage>
#include <QFile>
#include <QIcon>

#include "message.h"

namespace {

struct ImageProps {
    ImageProps(const QDBusArgument &arg)
    {
        arg.beginStructure();
        arg >> width;
        arg >> height;
        arg >> rowstride;
        arg >> hasAlpha;
        arg >> bitsPerSample;
        arg >> channels;
        arg >> data;
        arg.endStructure();
    }

    int width;
    int height;
    int rowstride;
    bool hasAlpha;
    int bitsPerSample;
    int channels;
    QByteArray data;
};

QPixmap getPixmapFromHint(QVariant argument)
{
    ImageProps props(argument.value<QDBusArgument>());

    return QPixmap::fromImage(QImage(reinterpret_cast<const uchar*>(props.data.constData()),
                                     props.width,
                                     props.height,
                                     QImage::Format_ARGB32).rgbSwapped());
}

} // namespace anonymous

Message::Message(int i, QString an, QString ic, QString hdr, QString bd, QVariantMap hs, QStringList as, int to, int iconSize)
    : timeout(to > 0 ? to : 3000),
      urgency(1),
      id(i),
      appName(an),
      text(bd),
      hints(hs),
      action(as),
      header(hdr),
      isComplete(false)
{
    bool ok = false;
    urgency = hints["urgency"].toInt(&ok) + 1;
    if (!ok)
        urgency = 1;

    if (!QPixmap(ic).isNull()) //Check if icon file is available, then check if it standart icon.
        icon = QPixmap(QIcon(ic).pixmap(iconSize));
    else if (!hints["icon_data"].isNull())
        icon = QPixmap(getPixmapFromHint(hints["icon_data"]));
    else if (!hints["image_data"].isNull())
        icon = QPixmap(getPixmapFromHint(hints["image_data"]));
    else if (!QIcon::fromTheme(ic).pixmap(iconSize).isNull())
        icon = QPixmap(QIcon::fromTheme(ic).pixmap(iconSize));
    else if (QFile::exists(":/images/"+ic+".svg") && !QIcon(":/images/"+ic+".svg").isNull())
        icon = QPixmap(QIcon(":/images/"+ic+".svg").pixmap(iconSize));
}
